<style>
    .tomcat_log {
        margin: 0px;
        width: 100%;
        height: 370px;
        background-color: #424251;
        overflow: auto;
        line-height: 22px;
        color: #fff;
        padding-left: 10px;
        font-family: arial;
        margin-top: 10px;
        outline: none;
    }

    .conter_box {
        display: none;
    }
</style>
<div class="bt-form">
    <div class="bt-w-main">
        <div class="bt-w-menu">
            <p class="bgw" name="service">服务状态</p>
            <p name="mgmt">管理面板</p>
            <p name="install">安装版本</p>
        </div>
        <div class="bt-w-con pd15">
            <div class="plugin_body">
                <div class="conter_box srs_service_box" name="service">
                    <div class="soft-man-con bt-form">
                        <p class="status">当前状态：
                            <span>开启</span>
                            <span style="color: #20a53a; margin-left: 3px;"
                                  class="glyphicon glyphicon glyphicon-play"></span>
                        </p>
                        <div class="sfm-opt">
                            <button class="btn btn-default btn-sm btn_server_start" style="display: none"
                                    onclick="bt.pub.set_server_status('srs_cloud','start')">启动
                            </button>
                            <button class="btn btn-default btn-sm btn_server_stop"
                                    onclick="bt.pub.set_server_status('srs_cloud','stop')">停止
                            </button>
                            <button class="btn btn-default btn-sm"
                                    onclick="bt.pub.set_server_status('srs_cloud','restart')">重启
                            </button>
                        </div>
                    </div>
                </div>
                <div class="conter_box install_version_box" name="install">
                    <button class="btn btn-success btn-sm va0 ml5 btn_install_srs">安装云SRS</button>
                    <textarea class="install_log tomcat_log" style="display:none"></textarea>
                    <ul class="help-info-text c7">
                        <li style="color:red">安装云SRS版本会耗时比较久，请耐心等候。</li>
                        <li style="color:red">若需要卸载云SRS，请直接删除云SRS插件。</li>
                    </ul>
                </div>
                <div class="conter_box srs_mgmt_box" name="mgmt">
                    <a href="#" class="btn btn-link srs_mgmt_link" target="_blank" rel="noreferrer">云SRS管理面板</a>
                </div>
            </div>
        </div>
    </div>
</div>
<script type="text/javascript">
  // Request the backend api by functionName with args.
  // @param timeout The timeout in ms, default to 300s.
  async function srs_cloud_request(functionName, args, timeout) {
    try {
      return await new Promise((resolve, reject) => {
        $.ajax({
          type: 'POST',
          url: `/plugin?action=a&s=${functionName}&name=srs_cloud`,
          data: args,
          timeout: timeout || 300 * 1000,
          success: function (res, status, xhr) {
            if (!res?.status) {
              return reject({xhr, err: JSON.stringify(res)});
            }
            return resolve(JSON.parse(res.msg));
          },
          error: function (xhr, status, err) {
            reject({xhr, err});
          },
        });
      });
    } catch ({xhr, err}) {
      console.error(`Call ${functionName} with args=${JSON.stringify(args)} err`, status, err, xhr);
      layer.msg(`Call ${functionName} with args=${JSON.stringify(args)} err ${err}`, {icon: 2});
      throw xhr;
    }
  }

  async function install_dependence(deps) {
    const depsContent = deps.map((dep, index) => {
      return `
          <li>
            ${index + 1}:
            <a href="javascript:void(0);" class="btlink" onclick="${dep.call}('${dep.id}')">
                安装${dep.title}
            </a>
          </li>
    `;
    }).join('\n');

    layer.closeAll();
    return new Promise((resolve, reject) => {
      layer.open({
        icon: 0,
        closeBtn: 0,
        title: '安装云SRS',
        area: '400px',
        btn: [],
        content: `
        <p>请安装以下依赖：</p>
        <ul>${depsContent}</ul>
        <p style="color: red; font-weight: bold;">请安装完依赖后继续安装云SRS。</p>
      `,
        success: function (layero, index) {
          // Note that this is called when the window is open, not closed or finished.
          resolve();
        },
      });
    });
  }

  async function installing_dependence(deps) {
    const depsContent = deps.map((dep, index) => {
      const desc = `正在安装<a href="javascript:void(0)" class="btlink" onclick="messagebox()">${dep.title}</a>`;
      return `<li>${index + 1}: ${desc}</li>`;
    }).join('\n');

    layer.closeAll();
    return new Promise((resolve, reject) => {
      layer.open({
        icon: 0,
        closeBtn: 0,
        title: '安装云SRS',
        area: '400px',
        btn: [],
        content: `
        <p>正在安装依赖：</p>
        <ul>${depsContent}</ul>
        请安装完依赖后，再继续安装云SRS，请点<a href="javascript:void(0)" class="btlink" onclick="messagebox()">这里</a>查看安装详情。
      `,
        success: function (layero, index) {
          // Note that this is called when the window is open, not closed or finished.
          resolve();
        },
      });
    });
  }
</script>
<script type="text/javascript">
  async function srs_cloud_init() {
    $(".bt-w-menu p").click(function () {
      srs_cloud_dispatch($(this));
    });

    $('.btn_install_srs').click(function () {
      srs_cloud_install();
    });

    const services = await srs_cloud_request('serviceStatus');
    console.log(`services is ${JSON.stringify(services)}`);
    if (!services?.srs || services?.r0) {
      $(".bt-w-menu p[name='install']").addClass('bgw').siblings().removeClass('bgw');
      $('.install_version_box').show().siblings().hide();
      await srs_cloud_setup_install_view();
    } else {
      await srs_cloud_dispatch($("p[name='service']"));
    }

    const pid = await srs_cloud_request('querySrs');
    console.log(`srs is ${JSON.stringify(services)}`);
    if (pid?.running) {
      await do_srs_cloud_install();
    }
  }

  async function srs_cloud_dispatch(self) {
    const menuName = self.attr('name');

    const services = await srs_cloud_request('serviceStatus');
    if (!services?.srs || services?.r0) {
      if (menuName !== 'install') layer.msg('请先安装云SRS', {icon: 7});
      return console.log(`service not ready ${JSON.stringify(services)}`);
    }

    self.addClass('bgw').siblings().removeClass('bgw');
    $(`.conter_box[name=${menuName}]`).show().siblings().hide();

    if (menuName === 'service') {
      await srs_cloud_setup_service_view();
    } else if (menuName === 'install') {
      await srs_cloud_setup_install_view();
    } else if (menuName === 'mgmt') {
      await srs_cloud_setup_mgmt_view();
    }
  }

  async function srs_cloud_setup_install_view() {
    const pid = await srs_cloud_request('querySrs');
    console.log(`installing pid is ${JSON.stringify(pid)}`);
    if (pid?.srs || pid?.running) {
      $('.btn_install_srs').html(pid?.srs ? '安装完成' : '正在安装').attr({'disabled': 'disabled'}).show();
      if (pid?.srs) {
        $('.install_log').hide();
      } else {
        $('.install_log').show();
      }
      return;
    }

    $('.btn_install_srs').html(pid?.r0 ? '重新安装云SRS' : '安装云SRS').removeAttr('disabled').show();
    if (pid.tail) {
      const elem = $('.install_log').val($('.install_log').val() + pid.tail).show();
      elem.get(0).scrollTop = elem.get(0)?.scrollHeight;
    }
  }

  async function srs_cloud_setup_service_view() {
    const r0 = await srs_cloud_request('querySrsService');
    console.log(`srs service is ${JSON.stringify(r0)}`);

    const status = !!(r0?.active);
    $('.srs_service_box .status .glyphicon').removeClass(status ? 'glyphicon-pause' : 'glyphicon-play')
      .addClass(status ? 'glyphicon-play' : 'glyphicon-pause').css('color', (status ? '#20a53a' : 'red'))
    $(!status ? '.btn_server_start' : '.btn_server_stop').show();
    $(status ? '.btn_server_start' : '.btn_server_stop').hide();
    $('.srs_service_box .status span:eq(0)').html(status ? '开启' : '停止');
  }

  async function srs_cloud_setup_mgmt_view() {
    const l = window.location;
    const url = `${l.protocol}//${l.hostname}/mgmt/`;
    $('.srs_mgmt_link').attr('href', url);
  }

  async function srs_cloud_install() {
    if ($('.install_log').empty()) {
      $('.install_log').show().val('Installing...\n');
    }

    let tips = layer.msg('检测服务状态', {icon: 16});
    const services = await srs_cloud_request('serviceStatus');
    console.log(`services status is ${JSON.stringify(services)}`);
    layer.close(tips);

    // We use default site, so it must be available.
    if (services?.default_site_available !== 'ok') {
      const msg = `默认站点不可用，请先将默认站点设置为空，当前站点${services?.site}`;
      layer.msg(msg, {icon: 2});
      throw msg;
    }

    // Request to install depends services.
    const deps = [
      ...(services?.nginx ? [] : [{id: 'nginx', title: 'NGINX', call: 'bt.soft.install'}]),
      ...(services?.node_manager ? [] : [{id: 'pm2', title: 'Node.js 16+', call: 'bt.soft.install'}]),
    ];
    // If no docker manager plugin, or docker service, install the plugin.
    if (!services?.docker_manager) {
      deps.push({id: 'docker', title: 'Docker', call: 'bt.soft.install'});
    }
    // For nodejs, user might not install any node version.
    if (services?.node_manager && !services?.node) {
      deps.push({id: 'nodejs', title: 'Node.js 16+', call: 'bt.soft.set_lib_config'});
    }

    const tasks = await srs_cloud_request('installTasks');
    const notInstalledDeps = deps.filter(dep => {
      if (tasks.filter(task => {
        return task?.name?.indexOf(`[${dep.id}-`) >= 0 ? task : null;
      }).length > 0) {
        return null;
      }
      return dep;
    });
    if (notInstalledDeps.length) {
      return await install_dependence(notInstalledDeps);
    }
    if (deps.length) {
      return await installing_dependence(deps);
    }

    // Try to install docker service.
    if (!services?.docker) {
      layer.msg('安装Docker服务', {icon: 1});
      await srs_cloud_request('installService', {service: 'docker'});
      await new Promise(resolve => setTimeout(resolve, 1000));
    }

    // Try to start docker service.
    if (!services?.docker_running) {
      layer.msg('启动Docker服务', {icon: 1});
      await srs_cloud_request('restartService', {service: 'docker'});
      await new Promise(resolve => setTimeout(resolve, 1000));
    }

    // Try to create site for srs cloud.
    if (!services?.site) {
      layer.msg('创建云SRS站点', {icon: 1});
      const site = await srs_cloud_request('createSrsSite');
      console.log(`Create site ${JSON.stringify(site)}`);
      await new Promise(resolve => setTimeout(resolve, 1000));
    }

    // Setup the website. Note that it depends on http configuration files.
    if (!services?.site_setup) {
      layer.msg('设置云SRS站点', {icon: 1});
      const data = await srs_cloud_request('setupSrsSite');
      console.log('setup site', data);
      await new Promise(resolve => setTimeout(resolve, 1000));
    }

    // Setup the firewall.
    if (!services?.firewall) {
      layer.msg('设置防火墙', {icon: 1});
      const data = await srs_cloud_request('setupFirewall');
      console.log('setup firewall', data);
      await new Promise(resolve => setTimeout(resolve, 1000));
    }

    // Allow user to install SRS, if not installed, or failed.
    if (!services?.srs || services?.r0) {
      return await do_srs_cloud_install();
    }
  }

  async function do_srs_cloud_install() {
    const installing = async (resolve, reject) => {
      $('.btn_install_srs').html('正在安装').attr({'disabled': 'disabled'});
      let pos = 1;
      for (; ;) {
        try {
          const pid = await srs_cloud_request('installSrs', {start: pos, end: pos + 100});
          console.log(`installing pid is ${JSON.stringify(pid)}`);

          if (pid.tail) {
            const elem = $('.install_log').val($('.install_log').val() + pid.tail);
            if (elem.get(0)?.scrollHeight) elem.get(0).scrollTop = elem.get(0).scrollHeight;
          }

          pos += pid.tail ? (pid.tail.match(/\n/g)?.length || 0) : 0;
          if (pid.srs) return resolve();

          if (pid.r0) {
            layer.msg('安装云SRS失败', {icon: 2});
            return reject(pid);
          }

          await new Promise(r0 => setTimeout(r0, 3000));
        } catch (e) {
          return reject(e);
        }
      }
    };

    const pid = await srs_cloud_request('querySrs');
    console.log(`installing pid is ${JSON.stringify(pid)}`);

    if (pid.r0) {
      await srs_cloud_request('cleanupIntall');
    }

    await new Promise((resolve, reject) => {
      installing(resolve, reject);
    });

    layer.msg('云SRS安装成功', {icon: 1});
    $('.btn_install_srs').html('安装完成').attr({'disabled': 'disabled'});
  }

  $(function () {
    srs_cloud_init();
  });
</script>

